-- 工具函数文件
local addonName, IWonew = ...

-- IWonew.UseFonts = "Interface\\AddOns\\WonewTigerHelper\\Fonts\\0b50eef8c531ddc8718039d2d1219ffd.ttf"
IWonew.UseFonts = "Interface\\AddOns\\WonewTigerHelper\\Fonts\\font_888.ttf"
IWonew.Temp_Vars = {
  needCraftLog = false
}

function IWonew.Log(message)
  local timeStamp = date("[%Y-%m-%d %H:%M:%S]")
  -- print(timeStamp)
  if not WonewTigerHelper_DB then
    WonewTigerHelper_DB = {}
  end

  -- print("WonewTigerHelper_DB", WonewTigerHelper_DB)
  table.insert(WonewTigerHelper_DB, timeStamp .. " " .. message)
end

function IWonew.PrintDebug(message)
  print("|cffffd700[Debug]:|r " .. tostring(message))
end

-- 函数：生成随机字符串
function IWonew.getRandomString(length)
  local chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" -- 可选字符集
  local result = {}
  for i = 1, length do
      local randIndex = math.random(1, #chars) -- 随机选择字符
      table.insert(result, chars:sub(randIndex, randIndex))
  end
  return table.concat(result) -- 拼接成字符串
end

function IWonew.TableToString(tbl)
  local result = "{"
  
  for key, value in pairs(tbl) do
      result = result .. "[" .. tostring(key) .. "] = "
      
      if type(value) == "table" then
          result = result .. IWonew.TableToString(value)  -- 递归调用
      else
          result = result .. tostring(value)
      end
      
      result = result .. ", "
  end
  
  -- 去掉最后的逗号和空格
  result = result:sub(1, -3) .. "}"
  
  return result
end

function IWonew.filterTable(tbl, filterFunc)
  local result = {}
  for _, value in ipairs(tbl) do
      if filterFunc(value) then
          table.insert(result, value)
      end
  end
  return result
end

function IWonew.contains(table, value)
  for _, v in ipairs(table) do
      if v == value then
          return true
      end
  end
  return false
end

function IWonew.concat(tbl1, tbl2)
  local newTbl = {}
  for i = 1, #tbl1 do
    table.insert(newTbl, tbl1[i])
  end
  for i = 1, #tbl2 do
    table.insert(newTbl, tbl2[i])
  end
  return newTbl
end

function IWonew.removeTableItem(tbl, item)
  local updateTbl = {}
  for i =0,  #tbl do
    if tbl[i] ~= item then
      table.insert(updateTbl, tbl[i])
    end
  end
  return updateTbl
end

-- 获取物品位置
function IWonew.GetItemSlot(targetItemID)
  local slotTable = nil
  -- 遍历所有背包槽（包括背包、银行等）
  for bagID = 0, NUM_BAG_SLOTS do
    -- 获取当前背包的槽位数
    local numSlots = C_Container.GetContainerNumSlots(bagID)
    -- 遍历当前背包的所有槽位
    for slotID = 1, numSlots do
        -- 获取当前槽位的物品 ID
        local itemID = C_Container.GetContainerItemID(bagID, slotID)
        -- print("itemID:", itemID, "targetItemID:", targetItemID)
        if itemID == targetItemID then
          local info = C_Container.GetContainerItemInfo(bagID, slotID)
          slotTable = {bagID = bagID, slotID = slotID, stackCount = info.stackCount, itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)}
          -- 输出物品的位置信息
          -- print(string.format("物品 %d 在背包 %d 的槽位 %d，位置: %s", targetItemID, bagID, slotID, itemLocation:GetDebugString()))
          
          -- 如果找到了目标物品，你可以在这里进行其他操作
          -- 例如，做一些物品检查或移动操作
      end
    end
  end
  return slotTable
end

function IWonew.FilterItemSlotByIDAndQuality(targetItemID, stackCount)
  local slotTable = {}
  -- 遍历所有背包槽（包括背包、银行等）
  for bagID = 0, NUM_BAG_SLOTS do
    -- 获取当前背包的槽位数
    local numSlots = C_Container.GetContainerNumSlots(bagID)
    -- 遍历当前背包的所有槽位
    for slotID = 1, numSlots do
        -- 获取当前槽位的物品 ID
        local itemID = C_Container.GetContainerItemID(bagID, slotID)
        -- print("itemID:", itemID, "targetItemID:", targetItemID)
        if itemID == targetItemID then
          local info = C_Container.GetContainerItemInfo(bagID, slotID)
          if stackCount == info.stackCount then
            table.insert(slotTable, {bagID = bagID, slotID = slotID, itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)})
          end
      end
    end
  end
  return slotTable
  -- containerInfo = C_Container.GetContainerItemInfo(containerIndex, slotIndex)  
end

function IWonew.GetAllBagItems()
  local items = {}
  for bagID = 0, NUM_BAG_SLOTS do
    -- 获取当前背包的槽位数
    local numSlots = C_Container.GetContainerNumSlots(bagID)
    -- 遍历当前背包的所有槽位
    for slotID = 1, numSlots do
      -- 获取当前槽位的物品 ID
      local itemID = C_Container.GetContainerItemID(bagID, slotID)
      if itemID then
        local itemName = C_Item.GetItemNameByID(itemID)
        local itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)
        local isBound = C_Item.IsBound(itemLocation)
        local info = C_Container.GetContainerItemInfo(bagID, slotID)
        table.insert(items, {itemID = itemID, itemName = itemName, isBound = isBound, stackCount = info.stackCount, itemLocation = itemLocation, bagID = bagID, slotID = slotID})
        
      end
    end
  end
  return items
end

function IWonew.GetFreeBagSlots()
  local freeSlots = {}
  for bagID = 0, NUM_BAG_SLOTS do
    -- 获取当前背包的槽位数
    local numSlots = C_Container.GetContainerNumSlots(bagID)
    -- 遍历当前背包的所有槽位
    for slotID = 1, numSlots do
        -- 获取当前槽位的物品 ID
        local itemID = C_Container.GetContainerItemID(bagID, slotID)
        if itemID == nil then
          table.insert(freeSlots, {bagID = bagID, slotID = slotID})
        end
    end
  end
  return freeSlots
end

function IWonew.GetItemSlotFromAccountBank(bagID, targetItemID)
  local numSlots = C_Container.GetContainerNumSlots(bagID)
  local slotTable = nil
  for slotID = 1, numSlots do
    local itemID = C_Container.GetContainerItemID(bagID, slotID)
    if itemID == targetItemID then
      slotTable = {bagID = bagID, slotID = slotID, itemLocation = ItemLocation:CreateFromBagAndSlot(bagID, slotID)}
    end
  end
  return slotTable
end

function IWonew.CreateTextFrame(size, textStr, offsetX, offsetY)
  -- 创建主框体
  local greenSquare = CreateFrame("Button", "GreenSquareFrame", UIParent)

  -- 设置框体大小和位置
  greenSquare:SetSize(size, size)         -- 宽度100，高度100
  greenSquare:SetPoint("TOPLEFT", offsetX, offsetY) -- 居中显示

  -- 设置框体背景颜色
  greenSquare.texture = greenSquare:CreateTexture(nil, "BACKGROUND")
  greenSquare.texture:SetAllPoints()   -- 填充整个框体
  greenSquare.texture:SetColorTexture(0, 0, 0, 1) -- 绿色 (R=0, G=1, B=0, A=1)

  local text = greenSquare:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
  text:SetFont(IWonew.UseFonts, 26, "OUTLINE")
  text:SetPoint("CENTER", greenSquare, "CENTER", 0, 0)  -- 设置文字在框架中心
  text:SetText(textStr)  -- 设置文字内容
  text:SetTextColor(1, 1, 1, 1)  -- 设置文字颜色为白色
  return greenSquare
end

function IWonew.CreateTextFrame2(size, textStr, offsetX, offsetY)

-- 创建框体
  local frame = CreateFrame("Frame", "MyBlackFrame", UIParent)
  frame:SetSize(size, size)  -- 设置框体大小（宽200px，高100px）
  frame:SetPoint("TOPLEFT", offsetX, offsetY)  -- 设置框体的位置（居中显示）

  -- 设置框体背景色为黑色
  frame:SetBackdrop({
      bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", -- 背景材质
      edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",  -- 边框材质
      tile = true, tileSize = 32, edgeSize = 32,
      insets = { left = 11, right = 12, top = 12, bottom = 11 },  -- 设置边距
  })
  frame:SetBackdropColor(0, 0, 0, 1)  -- 背景颜色为黑色（RGB）

  -- 创建文本标签
  local text = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  text:SetPoint("CENTER", frame, "CENTER", 0, 0)  -- 文本居中
  text:SetText(textStr)  -- 设置文本内容
  text:SetTextColor(1, 1, 1, 1)  -- 设置文本颜色为白色（RGB）
  return frame
end

function IWonew.slice(tbl, startIdx, endIdx)
  local result = {}
  for i = startIdx or 1, endIdx or #tbl do
      table.insert(result, tbl[i])
  end
  return result
end

function IWonew.getListItem(list, propName, propValue)
  local result = nil
  for i = 1, #list do
    if list[i][propName] == propValue then
      result = list[i]
      break
    end
  end
  return result
end

function IWonew.getCurrentTimeStr()-- /dump getCurrentTimeStr()
  local serverTime = GetServerTime()
  -- 使用 os.date 将时间戳转换为 "年-月-日 时:分:秒" 格式
  local formattedTime = date("%Y-%m-%d %H:%M:%S", serverTime)
  return formattedTime
end

function IWonew.deepCopy(t)
  local newTable = {}
  for k, v in pairs(t) do
      if type(v) == "table" then
          newTable[k] = IWonew.deepCopy(v)  -- 递归复制子表
      else
          newTable[k] = v  -- 复制非表值
      end
  end
  return newTable
end

function IWonew.GetBagMoney()
  local money = GetMoney()
  local gold = floor(money / 1e4)
  local silver = floor(money / 100 % 100)
  local copper = money % 100
  -- print(("You have %dg %ds %dc"):format(gold, silver, copper))
  return {gold = gold, silver = silver, copper = copper}
end

function IWonew.StringPartInList(targetStr, list)
  local isIn = false
  for i = 1, #list do
    if string.find(targetStr, list[i]) then
      isIn = true
      break
    end
  end
  return isIn
end


